package com.ptswitch.material.pages.bom;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.upload.services.UploadedFile;
import org.hxzon.project.AppRuntimeException;
import org.slf4j.Logger;
import org.springframework.dao.DataAccessException;

import com.ptswitch.material.model.base.Upload;
import com.ptswitch.material.model.material.Bom;
import com.ptswitch.material.model.material.BomOrigFile;
import com.ptswitch.material.pages.base.PageBase;
import com.ptswitch.material.service.BomService;
import com.ptswitch.material.service.MaterialExcelService;
import com.ptswitch.material.util.WebUtil;

public class ValidateIndustryLevel extends PageBase {
    @Inject
    private Logger logger;
    @Inject
    private MaterialExcelService excelSer;
    @Inject
    private BomService bomSer;
    @Property
    private UploadedFile file;

    @OnEvent(value = EventConstants.ACTIVATE)
    Object init() {
        return null;
    }

    @OnEvent(value = EventConstants.SUCCESS)
    Object validateBom() {
        Bom bom = new Bom();
        bom.setCode("validate");
        bom.setVersion("validate");
        BomOrigFile upload = WebUtil.upload(file, BomOrigFile.class);
        upload.setUser(null);// to fix
        try {
            excelSer.buildBomFromExcel(bom, WebUtil.getRealFilePath(upload));
        } catch (Throwable e) {
            WebUtil.delete(upload);
            throw AppRuntimeException.rethrow("读取单板表文件错误", e);
        }
        try {
            bom.setOrigFile(upload);
            bomSer.saveEx(bom);
        } catch (Throwable e) {
            if (e instanceof DataAccessException) {
                e = e.getCause().getCause();
            }
            throw AppRuntimeException.rethrow("校验单板表异常", e);
        }
        //download
        bom = bomSer.findById(bom.getId(), BomService.Init_BomMaterials);// for init bm.material
        Upload download = new Upload();
        download.setFilePath("output/validate.xls");
        download.setFileName("validate.xls");
        download.setFileType("application/vnd.ms-excel");
        excelSer.outputBom(WebUtil.getRealFilePath(download), bom, MaterialExcelService.OutputBomError_IndustryLevel);
        //delete db
        bomSer.delete(bom);
        return WebUtil.download(download);
    }
}
